package com.rinvay.asdownloader.service;

import java.util.ArrayList;
import java.util.Iterator;

import com.rinvay.asdownloader.core.Core;
import com.rinvay.asdownloader.core.network.NetworkManager;
import com.rinvay.asdownloader.persistent.DownloadTaskDAO;
import com.rinvay.asdownloader.platform.AndroidFactory;
import com.rinvay.network.filedownload.FileDownloadManager;
import com.rinvay.utils.logger.Log;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Binder;
import android.os.IBinder;

public class DownloadService extends Service
{
    private static final String TAG = "DownloadService";

    public class DownloadBinder extends Binder
    {

        public FileDownloadManager getDownloadMgr() {
            return Core.getInstance().getFileDownloadManager();
        }

    }

    public void onCreate() {
        super.onCreate();

        Log.i(TAG, " onCreate");
        AndroidFactory.setApplicationContext(getApplication());

        startCore();

    }

    public IBinder onBind(Intent intent) {
        Log.i(TAG, " onBind");
        return new DownloadBinder();
    }

    public void onDestroy() {
        Log.i(TAG, " onDestroy");
        stopCore();

        super.onDestroy();
    }

    private synchronized void startCore() {
        if (Core.getInstance() != null) {
            return;
        }

        DownloadTaskDAO.createInstance(getApplicationContext());

        Core.createInstance();
        Core.getInstance().startCore();
    }
    
    private synchronized void stopCore() {
        if(Core.getInstance() == null) {
            return;
        }
        Core.terminate();
    }

}
